#include "ControlTU.h"
#include "CPU.h"
#include <iostream>

using namespace std;
	CPU* ControlTU::cpu;
	short ControlTU::RB_Pointer;
	short ControlTU::Offset;
	short ControlTU::Condition;


ControlTU::ControlTU()
{
}

ControlTU::~ControlTU()
{
}

void ControlTU::setCPU(CPU* proc)
{
	cpu = proc;
}

void ControlTU::loadParamIV()
{
	short inst = cpu->getIR();
	Condition = (inst & 0x0f00) >> 8;
	Offset = inst & 0x00ff;
}
void ControlTU::loadParamV()
{
	short inst = cpu->getIR();
	Offset = inst & 0x0fff;
}
void ControlTU::loadParamVI()
{
	short inst = cpu->getIR();
	RB_Pointer = inst & 0x0007;
}
void ControlTU::Fjfcond()
{
	ControlTU::loadParamIV();
	if(Offset & 0x0080)
		Offset = Offset | 0xff00;
	switch(Condition) {
	case 4:
		if(!cpu->getFlagNeg())
			cpu->setPC(cpu->getPC()+ Offset);
		break;
	case 5:
		if(!cpu->getFlagZero())
			cpu->setPC(cpu->getPC()+ Offset);
		break;
	case 6:
		if(!cpu->getFlagCarry())
			cpu->setPC(cpu->getPC()+ Offset);
		break;
	case 7:
		if(!cpu->getFlagNegZero())
			cpu->setPC(cpu->getPC()+ Offset);
		break;
	case 0:
		if(!cpu->getFlagTrue())
			cpu->setPC(cpu->getPC()+ Offset);
		break;
	case 3:
//		cout << "CCCCCCCCCCCCCCCCCCCCCCCCCCCCC-" << !cpu->getFlagOverflow() <<  endl;
		if(!cpu->getFlagOverflow()) {
		//	cout << "ENTREI AKI!!!" << endl;
			cpu->setPC(cpu->getPC()+ Offset);
		}
		else
		//	cout << "NAO ENTREI NO IF" << endl;
		break;
	}
}
void ControlTU::Fjtcond()
{
	ControlTU::loadParamIV();
	if(Offset & 0x0080)
		Offset = Offset | 0xff00;
	switch(Condition) {
		case 4:
			if(cpu->getFlagNeg())
				cpu->setPC(cpu->getPC()+ Offset);
			break;
		case 5:
			if(cpu->getFlagZero())
				cpu->setPC(cpu->getPC()+ Offset);
			break;
		case 6:
			if(cpu->getFlagCarry())
				cpu->setPC(cpu->getPC()+ Offset);
			break;
		case 7:
			if(cpu->getFlagNegZero())
				cpu->setPC(cpu->getPC()+ Offset);
			break;
		case 0:
			if(cpu->getFlagTrue())
				cpu->setPC(cpu->getPC()+ Offset);
			break;
		case 3:
			if(cpu->getFlagOverflow())
				cpu->setPC(cpu->getPC()+ Offset);
			break;
		}
}
void ControlTU::Fjump()
{
	ControlTU::loadParamV();
	if(Offset & 0x0800)
		Offset = Offset | 0xf000;
	
	cpu->setPC(cpu->getPC()+ Offset);	
}
void ControlTU::Fjal()
{
	ControlTU::loadParamVI();
	unsigned short aux;
//	cout << " Tou no Jump and Link" <<endl;
//	cout << " RB = " << RB_Pointer <<endl;
	aux = cpu->readRegister(7);
	cpu->setWBRegister(7);
	cpu->setWBValue(cpu->getPC());
	cpu->setshallWB(true);
	//cpu->setRegister(7,cpu->getPC());
	if(RB_Pointer == 7)
		cpu->setPC(aux);
	else
		cpu->setPC(cpu->readRegister(RB_Pointer));
}
void ControlTU::Fjr()
{
	ControlTU::loadParamVI();
//	cout << " Tou no Jump Register" << endl;
//	cout << " REG# = " << RB_Pointer << endl;
//	cout << " VALUE = " << cpu->readRegister(RB_Pointer) << endl;
	cpu->setPC(cpu->readRegister(RB_Pointer));
	
}
